/**
 * @author robin
 * @file index
 * @date 2018-09-26 10:10
 */
import * as React from "react";
import * as ReactDOM from "react-dom";
import { LocaleProvider } from "antd";

import zhCN from "antd/lib/locale-provider/zh_CN";
import moment from "moment";
import "moment/locale/zh-cn";
import { httpCommonClient } from "./common/axios";
import configureStoreCreater from "./common/store";
import appCreater from "./component/app";
import { AxiosResponse } from "axios";

moment.locale("zh-cn");

export default async options => {
  const [configureStore, App] = await Promise.all([
    configureStoreCreater(options),
    appCreater(options)
  ]);
  httpCommonClient
    .post("/getStore")
    .then(
      (response: AxiosResponse): any => {
        if (response.status === 200 && response.data.success) {
          const data = response.data.data;
          return configureStore({
            session: data.session,
            menus: data.menus,
            dictionary: [
              ...data.dictionary,
              ...data.apps.map(r => ({
                tableName: "t_app",
                colName: "app_id",
                key: r.id,
                value: r.appName
              })),
              ...data.orgs.map(r => ({
                tableName: "t_org",
                colName: "org_id",
                key: r.id,
                value: r.orgName
              })),
              ...data.roles.map(r => ({
                tableName: "t_role",
                colName: "role_id",
                key: r.id,
                value: r.roleName
              }))
            ]
          });
        }
        return Promise.reject();
      }
    )
    .catch(
      (error: any): any => {
        const { response } = error;
        if (response && response.status === 401) {
          return configureStore({});
        } else {
          window.alert("页面初始化失败，请联系管理员");
          return Promise.reject();
        }
      }
    )
    .then(store => {
      ReactDOM.render(
        <LocaleProvider locale={zhCN}>
          <App store={store} />
        </LocaleProvider>,
        document.getElementById("root") as HTMLElement
      );
    });
};
